package e2q.security.web.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;
import java.util.Properties;

import org.springframework.util.StringUtils;

import sun.misc.BASE64Encoder;

/**
 * 
 * 
 * 
 * @author 88250 <DL88250@gmail.com>
 * 
 */

public class Base64PasswordEncoder {

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',

	'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'

	};

	private final String encodingAlgorithm;

	private String characterEncoding;

	public Base64PasswordEncoder(final String encodingAlgorithm) {

		this.encodingAlgorithm = encodingAlgorithm;

	}

	public String encode(final String password) {

		if (password == null) {

			return null;

		}
		String pwd="";
		Properties p = new Properties(); 
		try {
//			p.load(in);
 
       	  InputStream   is   =   getClass().getResourceAsStream("/initInfo.properties");    
       	  p.load(is);  
       	  is.close();
			if(p.getProperty("isCiphertext").equals("true")){

				try {

					MessageDigest messageDigest = MessageDigest
							.getInstance(this.encodingAlgorithm);

					if (StringUtils.hasText(this.characterEncoding)) {

						messageDigest.update(password.getBytes(this.characterEncoding));

					} else {

						messageDigest.update(password.getBytes());

					}

					final byte[] digest = messageDigest.digest();

					pwd=getFormattedText(digest);

				} catch (final NoSuchAlgorithmException e) {

					throw new SecurityException(e);

				} catch (final UnsupportedEncodingException e) {

					throw new RuntimeException(e);

				}
			
				
			}else{
				pwd=password;
			}
			
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		return pwd;

	}

	/**
	 * 
	 * Takes the raw bytes from the digest and formats them correct.
	 * 
	 * 
	 * 
	 * @param bytes
	 *            the raw bytes from the digest.
	 * 
	 * @return the formatted bytes.
	 * 
	 */

	private String getFormattedText(byte[] bytes) {

		final StringBuilder buf = new StringBuilder(bytes.length * 2);

		sun.misc.BASE64Encoder e = new BASE64Encoder();

		final String buf2 = e.encode(bytes);

		for (int j = 0; j < bytes.length; j++) {

			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);

			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);

		}

		System.out.println("Final: " + buf2);

		System.out.println(encodingAlgorithm + ": " + buf);

		return buf2.toString();

	}

	public final void setCharacterEncoding(final String characterEncoding) {

		this.characterEncoding = characterEncoding;

	}

}
